package com.hust360.percent.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.widget.ListView;

import com.hust360.percent.PercentApplication;
import com.hust360.percent.R;
import com.hust360.percent.adapter.AreaListAdapter;
import com.hust360.percent.pojo.Area;
import com.hust360.percent.pojo.Area.AreaDAO;
import com.hust360.percent.utils.ActivityUtils;

public class AreaActivity extends Activity {

	/**
	 * 显示区域的list view
	 */
	ListView listView;

	/**
	 * 显示区域的list view的适配器
	 */
	AreaListAdapter adapter;

	/**
	 * 普通多线程通信的句柄
	 */
	Handler handler = new Handler();

	/**
	 * list view对应的数据
	 */
	List<Area> list;

	/**
	 * Percent Application实例的强引用
	 */
	PercentApplication application;

	/**
	 * Area访问数据库的操作类
	 */
	AreaDAO areaDAO;
	
	/**
	 * 缓存city id
	 */
	Long cityId = -1L;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		ActivityUtils.addActivity(this);
		setContentView(R.layout.activity_area);
		listView = (ListView) findViewById(R.activity_area.listview);
		list = new ArrayList<Area>();
		application = (PercentApplication) getApplication();
		areaDAO = application.getAreaDAO();
		cityId = application.getCurCity().id;
		
		/*
		 * 测试所用代码
		 */
		adapter = new AreaListAdapter(this, list);
		listView.setAdapter(adapter);

		/*--------------------多线程加载数据------------------*/
		application.getThreadPool().execute(new Runnable() {

			@Override
			public void run() {
				List<Area> tmpList = areaDAO.findByArgs(null, Area.CITY_ID
						+ "='" + cityId + "'", null, null,
						null, null);
				synchronized (list) {
					list = tmpList;
					handler.post(new Runnable() {
						@Override
						public void run() {
							adapter.setList(list);
							adapter.notifyDataSetChanged();
						}
					});
				}
			}
		});
	}
	
	/**
	 * 重新加载区域信息。方法内部使用多线程方式
	 */
	private void reloadArea() {
		application.getThreadPool().execute(new Runnable() {

			@Override
			public void run() {
				List<Area> tmpList = areaDAO.findByArgs(null, Area.CITY_ID
						+ "='" + cityId + "'", null, null,
						null, null);
				synchronized (list) {
					list = tmpList;
					handler.post(new Runnable() {
						@Override
						public void run() {
							adapter.setList(list);
							adapter.notifyDataSetChanged();
						}
					});
				}
			}
		});
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		if (cityId != application.getCurCity().id) {
			cityId = application.getCurCity().id;
			reloadArea();
		}
	}

	@Override
	protected void onDestroy() {
		ActivityUtils.removeActivity(this);
		super.onDestroy();
	}

}
